package org.example.net;

import lombok.SneakyThrows;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @Auther:Liu
 * @Testname:DemoC2
 * @Date:2025/8/27 17:29
 */
public class DemoC2  {

    @SneakyThrows
    public static void main(String[] args) {
        Socket socket = new Socket("127.0.0.1", 8890);
        System.out.println("通讯已开启");
        new Thread(() -> {
            try {
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = new byte[1024];
                while (true){
                    int len = inputStream.read(bytes);
                    String s = new String(bytes, 0, len, StandardCharsets.UTF_8);
                    System.out.println(s);
                    if ("bye".equals(s)) {
                        break;
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }).start();

       new Thread(() -> {
           //发送内容
           try {
               OutputStream outputStream = socket.getOutputStream();
               Scanner scanner = new Scanner(System.in);
               while(true){
                   System.out.println("Input:");
                   String message = scanner.nextLine();
                   outputStream.write(message.getBytes(StandardCharsets.UTF_8));
                   if ("bye".equals(message)) {
                       break;
                   }
               }
           } catch (IOException e) {
               throw new RuntimeException(e);
           }
       }).start();
    }
}
